#pragma once
#include "Types.hpp"
#include <atomic>
#include <functional>  // ✅ 提供 std::function
#include <map>         // ✅ 提供 std::map
#include <vector>      // ✅ 提供 std::vector
#include <cstdint>     // ✅ 提供 uint8_t
#include <string>      // ✅ 提供 std::string

namespace linkfabric {
constexpr int MAX_CHANNELS = 64;
constexpr int MAX_PAYLOAD = 4096;

struct Channel {
    std::atomic<uint32_t> futex_flag;
    uint32_t length;
    ChannelPermission permission;
    uint8_t payload[MAX_PAYLOAD];
};

struct SharedMemory {
    std::atomic<uint32_t> channel_bitmap;
    Channel channels[MAX_CHANNELS];
};

class MemLink {
public:
    bool init(const std::string& devicePath);
    int allocChannel(ChannelPermission perm);
    void freeChannel(int channelId);
    bool write(int channelId, const std::vector<uint8_t>& data);
    void onData(int channelId, std::function<void(const std::vector<uint8_t>&)> callback);
    void run();
    void shutdown();

private:
    SharedMemory* shm_ = nullptr;
    int fd_ = -1;
    std::map<int, std::function<void(const std::vector<uint8_t>&)>> callbacks_;
};
}